package restlet;

import java.util.ArrayList;
import java.util.Vector;

import javax.jdo.PersistenceManager;

import model.Mesto;
import model.Prevoznik;
import model.PutnaDuz;
import model.Util;
import model.VrstaPrevoza;

import org.restlet.resource.ServerResource;

import restlet.interfaces.TripPartResourceI;
import app.PMF;
import beans.TripPartBean;

import com.google.appengine.api.datastore.Key;

public class TripPartResource extends ServerResource implements TripPartResourceI {
	@Override
	public Vector<TripPartBean> allTripParts() {
		
		System.out.println("TripPartResource, pristiglo: " + getQuery());

		Vector<TripPartBean> tripParts = new Vector<TripPartBean>();
		for(PutnaDuz tp : Util.getAllEntitiesFromTable(PutnaDuz.class)){
			tripParts.add(tp.toTripPartBean());
		}
		return tripParts;
	}

	@Override
	public void addTripPart(TripPartBean tripPart) {

		getLogger().warning("TripPartResource123,place: " + tripPart);
		
		try {
			System.out.println("Primljeno: " + tripPart);
			PersistenceManager pm = PMF.get().getPersistenceManager();

			//ako primimo putnu liniju za koju nemamo mesto, nije nam od znacaja
			Mesto mestoOd = Util.getMestoFromName(tripPart.getMestoOd().getNaziv());
			Mesto mestoDo = Util.getMestoFromName(tripPart.getMestoDo().getNaziv());

			if(mestoOd == null || mestoDo == null){
				System.out.println("Odbacujemo putnu duz sa mestima: " +
						tripPart.getMestoOd().getNaziv() +" , " + tripPart.getMestoDo().getNaziv());
				return;
			}

			Prevoznik prev = Util.getCarrierFromName(tripPart.getPrevoznik().getNaziv());

			//ako trebamo da dodamo novog prevoznika
			if(prev == null){
				VrstaPrevoza tempVp = Util.getEnityByFieldEqualsValue(VrstaPrevoza.class, "naziv", "Bus");
				//String vpID = tripPart.getPrevoznik().getVrstaPrevoza().getID()+"";
				prev = new Prevoznik(tripPart.getPrevoznik().getNaziv(),tempVp.getSifra());
				//Util.getEntityFromTableByID(VrstaPrevoza.class, vpID).getSifra());
				pm.makePersistent(prev);
				System.out.println("Novi prevoznik: " + prev);
				;
			}

			PutnaDuz pd = new PutnaDuz(tripPart.getCena(), tripPart.getPolazak(),
					tripPart.getDolazak(), new ArrayList<Key>(),
					mestoOd.getSifra(), mestoDo.getSifra(), prev.getSifra());

			pm.makePersistent(pd);
			System.out.println("Dodata putna duz: " + pd);
			pm.close();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}
}
